//
//  MITimerButton.m
//  BestMovement
//
//  Created by 肖剑 on 15/3/4.
//  Copyright (c) 2015年 MakingIt. All rights reserved.
//

#import "MITimerButton.h"

@interface MITimerButton (){
    __weak NSTimer *_timer;
    NSInteger _counter;
    NSString *_title;
}


@end

@implementation MITimerButton

- (void)dealloc{
    [_timer invalidate];
    _timer = nil;
}


- (id)init{
    self = [super init];
    if (self) {
        _timeInterval = 60;
        _isCountiue = YES;
        [self setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [self.titleLabel setFont:[UIFont systemFontOfSize:13]];
    }
    return self;
}

+ (id)buttonWithType:(UIButtonType)buttonType{
    return [[MITimerButton alloc] init];
}

- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents{
    [super addTarget:target action:action forControlEvents:controlEvents];

    if (!_isCountiue) {
        return;
    }
    [super addTarget:self action:@selector(timerButtonPressed) forControlEvents:controlEvents];
}

- (void)setIsCountiue:(BOOL)isCountiue
{
    _isCountiue = isCountiue;
    if (isCountiue) {
        [self timerButtonPressed];
    }
}

- (void)timerButtonPressed{
    [self setEnabled:NO];
    [self setTitleColor:kColorRGBA(255, 128, 0, 1) forState:UIControlStateNormal];
    _counter = _timeInterval;
    _title = [self.titleLabel text];
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                              target:self
                                            selector:@selector(timerCountDown)
                                            userInfo:nil
                                             repeats:YES];
    
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    
}

- (void)removeFromSuperview{
    if ([_timer isValid]) {
        [_timer invalidate];
        _timer = nil;
    }
}

- (void)timerCountDown{
    
    _counter--;
    
    NSString *titleString = [NSString stringWithFormat:@"%ld秒后重新获取",_counter];
    [self setTitle:titleString forState:UIControlStateNormal];
    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0) {
        [self setEnabled:YES];
        [self setUserInteractionEnabled:NO];
    }
    
    if (_counter <= 0) {
        [self setTitle:@"重新获取" forState:UIControlStateNormal];
        [self setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [self setEnabled:YES];
        [self setUserInteractionEnabled:YES];
        [_timer invalidate];
        _timer = nil;
    }
}

@end
